<template>
  <ul pager-component class="pager">    
    <li ><button @click="setPage(current-1)" :disabled="current<=1">&lt;</button></li>
    <li v-for="(v,i) in pages" :key="i"><button @click="setPage(v)" :class="{active:current===v}" :disabled="v==='...'">{{v}}</button></li>
    <li><button @click="setPage(current+1)" :disabled="current>=all">&gt;</button></li>
  </ul>
</template>

<script>

export default {
    props:[
        'page',
        'size',
        'total'
    ],
    data() {
        return {
            current:1,
            pages:[]
        }
    },
    computed:{
        all(){
            var _total = this.total || 1;
            var _size = this.size || 10;
            return _size > 0 ? Math.ceil(_total/_size) : 1;
        }
    },
    methods: {
        reload(){
            var pages = [];
            var _all = this.all;
            for(var p = 1; p <= _all; p++){
                if(p == 1){
                    pages.push(p);
                }else if(p == this.current - 3){
                    pages.push('...');
                }else if(p > this.current - 3 && p < this.current + 3){
                    pages.push(p);
                }else if(p == this.current + 3){
                    pages.push('...');
                }else if(p == _all){
                    pages.push(p);
                }
            }
            this.pages = pages;
        },

        setPage(p){
            if(this.current != p){
                this.current = p;
                this.reload();
                this.$emit('on-page-changed', p);
            }
        }
    },
    watch:{
        page(v){
            this.current = parseInt(v) || 1;
            this.$nextTick(x=>this.reload());
        },
        total(v){
            this.$nextTick(x=>this.reload());
        },
        size(v){
            this.$nextTick(x=>this.reload());
        }
    },
    /**
     * 组件完成创建
    */
    mounted(){
        this.current = parseInt(this.page) || 1;
        this.reload();
    }
};
</script>

<style scoped>
[pager-component] {
  height: 38px;
  padding: 3px;
}

.pager li{
    display: inline-block;
}

.pager li > button{
    width: 24px;
    height: 24px;
    line-height: 24px;
    border: none;
    border-radius: 12px;
    color: #fff;
    background: darkgray;
    outline: none;
}

.pager li > button:hover{
    background: royalblue;
}

.pager li > button.active{
    background: royalblue;
}

.pager li > button:disabled{
    background: darkgray;
}

</style>